/**
 * 
 */
package ua.kpi.javatrainee6.model.people;

/**
 * Sending messages to Observers which are registered for it
 */
public class Observers {
	
	private int capacity = 10;
	private int observerNumber = 0;
	private Observer[] observers;
	
	public Observers() {
		observers = new Observer[capacity];
	}
	
	private int indexOf(Observer observer) {
		for (int i = 0; i < observerNumber; i++) {
			if (observer.equals(observers[i])) {
				return i;
			}
		}
		return -1;
	}
	
	private void changeCapacity() {
		if (observerNumber == capacity) {
			   Observer[] newObservers = new Observer[2 * capacity];
			   System.arraycopy(observers, 0, newObservers, 0, capacity);
			   capacity = 2 * capacity;
			   observers = newObservers;
		   }
	}
	
	public void add(Observer observer) {
	   changeCapacity();
	   if (indexOf(observer) == -1) {
		   observers[observerNumber] = observer;
		   observerNumber++; 
	   } 
	}
	
	public void remove(Observer observer) {
		if (indexOf(observer) == -1) {
			return;
		}
		Observer[] newObservers = new Observer[capacity];
		int index = 0;
		for (int i = 0; i < observerNumber; i++) {
			if (!observers[i].equals(observer)) {
				newObservers[index] = observers[i];
				index++;
			}
		}
		observers = newObservers;
		observerNumber--;
	}
	
	public void informAll() {
		for (int i = 0; i < observerNumber; i++) {
			observers[i].update();
		}
	}
}
